package main

import (
	"strconv"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/widget"
	"github.com/zhaocy/fyne-theme"
)

// 数据绑定的功能就可以做打字应用了

func main() {
	myApp := app.New()
	myApp.Settings().SetTheme(themex.Themex())
	myWin := myApp.NewWindow("databinding")

	//lable 数据绑定
	bd := binding.NewString()
	lbl := widget.NewLabelWithData(bd)
	input := widget.NewEntryWithData(bd)

	// 设置默认的绑定数据
	bd.Set("这是默认值")

	// 监听 label
	listenLbl := widget.NewLabel("")

	// 给label添加监听方法
	bd.AddListener(binding.NewDataListener(func() {
		s, err := bd.Get()
		if err != nil {
			fyne.LogError("get err", err)
			return
		}
		listenLbl.SetText(s)
	}))

	sl := binding.NewStringList()
	l := widget.NewListWithData(sl, nil, nil)

	//创建list item，使用label
	l.CreateItem = func() fyne.CanvasObject {
		return widget.NewLabel("")
	}

	// 更新项目
	l.UpdateItem = func(id widget.ListItemID, item fyne.CanvasObject) {
		// 获取Item值
		di, _ := sl.GetValue(id)

		if l2,ok := item.(*widget.Label);ok{
			l2.SetText(di)
		}
	}

	i := 0
	btn := widget.NewButton("添加", func() {
		sl.Append("item " + strconv.Itoa(i))
		i++
	})

	//binding struct
	dog:= &Dog{"lucky",2}
	bs:= binding.BindStruct(dog)

	lblDog:= widget.NewLabel("")
	dogBtn:= widget.NewButton("绑定Dog",func() {
		// 获取Name
		iname, _ := bs.GetValue("Name")
		if name,ok:=iname.(string);ok{
			lblDog.SetText(name)
		}
	})

	//layout
	c := container.NewBorder(container.NewVBox(
		listenLbl,
		lbl,
		input,
		btn,
		container.NewHBox(dogBtn,lblDog),
	), nil, nil, nil, l)
	myWin.SetContent(c)
	myWin.Resize(fyne.NewSize(550, 450))
	myWin.ShowAndRun()
}

// 注意 结构体的字段需要大写，否则绑定后是获取不到的
type Dog struct{
	Name string
	Age int
}